package com.zhong.media;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.zhong.media.download.DownloadListener;
import com.zhong.media.download.OkHttpManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;


public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private EditText urlEt;
    private RadioGroup playTypeRg;
    private Button downloadBtn;
    private Button selectLoaclFileBtn;

    private ProgressDialog progressDialog;

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        urlEt = (EditText) findViewById(R.id.video_url_et);
        playTypeRg = (RadioGroup) findViewById(R.id.play_type_rg);
        downloadBtn = findViewById(R.id.download_btn);
        selectLoaclFileBtn = findViewById(R.id.select_local_file_btn);

        ((RadioGroup) findViewById(R.id.radio_group)).setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                urlEt.setText(((RadioButton) findViewById(checkedId)).getText().toString().trim());
            }
        });

        findViewById(R.id.btn).setOnClickListener(onClick);
        downloadBtn.setOnClickListener(onClick);
        selectLoaclFileBtn.setOnClickListener(onClick);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    }

    OnClickListener onClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.select_local_file_btn:
                    String videoFilePath;
                    if (isSDCardEnable()) {
                        videoFilePath = Environment.getExternalStorageDirectory() + "/VideoDemoDownload";
                    } else {
                        videoFilePath = getFilesDir().getAbsolutePath();
                    }

                    File videoFile = new File(videoFilePath);
                    if(!videoFile.exists() || videoFile.isFile() || videoFile.listFiles().length <= 0){
                        Toast.makeText(MainActivity.this, "未发现本地文件", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    File[] files = videoFile.listFiles();
                    final List<String> filesAbsolutePath = new ArrayList<>();
                    for(File file : files){
                        String fileAbsolutePath = file.getAbsolutePath();
                        if(isVideo(fileAbsolutePath)){
                            filesAbsolutePath.add(fileAbsolutePath);
                        }
                    }

                    showListDialog(filesAbsolutePath.toArray(new String[filesAbsolutePath.size()]), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            urlEt.setText(filesAbsolutePath.get(which));
                        }
                    });
                    break;
                case R.id.download_btn:
                    String url = urlEt.getText().toString().trim();
                    if (TextUtils.isEmpty(url)) {
                        Toast.makeText(MainActivity.this, "先输入地址", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!url.contains("http://")) {
                        Toast.makeText(MainActivity.this, "不是正确网络地址，不进行下载", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    String filePath;
                    if (isSDCardEnable()) {
                        filePath = Environment.getExternalStorageDirectory() + "/VideoDemoDownload";
                    } else {
                        filePath = getFilesDir().getAbsolutePath();
                    }

                    OkHttpManager.downloadAsync(url, filePath, new OkHttpManager.DataCallBack() {

                        @Override
                        public void requestFailure(Request request, Exception e) {
                            Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                            dismissProgressDialog();
                        }

                        @Override
                        public void requestSuccess(String result) throws Exception {
                            Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                            dismissProgressDialog();
                        }
                    }, new DownloadListener() {

                        @Override
                        public void onProgress(final int progres, String fileName) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showProgressDialog(progres);
                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });

                    break;
                case R.id.btn:
                    playVideo();
                    break;

            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    /**
     * 判断是否是视频文件
     * @param extension 后缀名
     * @return
     */
    public static boolean isVideo(String extension) {
        if (extension == null)
            return false;

        final String ext = extension.toLowerCase();
        if (ext.endsWith("mpeg") || ext.endsWith("mp4") || ext.endsWith("mov") || ext.endsWith("m4v") ||
                ext.endsWith("3gp") || ext.endsWith("3gpp") || ext.endsWith("3g2") ||
                ext.endsWith("3gpp2") || ext.endsWith("avi") || ext.endsWith("divx") ||
                ext.endsWith("wmv") || ext.endsWith("asf") || ext.endsWith("flv") ||
                ext.endsWith("mkv") || ext.endsWith("mpg") || ext.endsWith("rmvb") ||
                ext.endsWith("rm") || ext.endsWith("vob") || ext.endsWith("f4v")) {
            return true;
        }
        return false;
    }


        private void showListDialog(String[] list, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("选择本地文件");

        builder.setItems(list, onClickListener);
        builder.show();
    }

    /**
     * dismiss ProgressDialog
     */
    private void dismissProgressDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * show ProgressDialog
     *
     * @param progress
     */
    private void showProgressDialog(int progress) {
        if (null == progressDialog) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setTitle("正在下载");
            progressDialog.setMessage("请稍后...");
            progressDialog.setProgress(0);
            progressDialog.setMax(100);
        }

        if (progressDialog.isShowing()) {
            progressDialog.setProgress(progress);
        } else {
            progressDialog.show();
        }
    }

    /**
     * go to video activity
     */
    private void playVideo() {
        String url = urlEt.getText().toString().trim();
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(MainActivity.this, "先输入地址", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent();
        switch (playTypeRg.getCheckedRadioButtonId()) {
            case R.id.play_type_a:
                intent.setClass(MainActivity.this, MyVideoActivity.class);
                break;
            case R.id.play_type_z:
                intent.setClass(MainActivity.this, ZPlayerActivity.class);
                break;
            case R.id.play_type_b:
                intent.setClass(MainActivity.this, MediaPlayerActivity.class);
                break;
            case R.id.play_type_c:
                intent.setClass(MainActivity.this, TextureViewActivity.class);
                break;
            case R.id.play_type_d:
                try {
//					 	intent = new Intent(Intent.ACTION_VIEW);
//				        String type = "video/* ";
//				        Uri uri = Uri.parse(url);
//				        intent.setDataAndType(uri, type);
//				        startActivity(intent);

                    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
                    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                    Intent mediaIntent = new Intent(Intent.ACTION_VIEW);
                    mediaIntent.setDataAndType(Uri.parse(url), "video/*");
                    startActivity(mediaIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "未找到系统播放器", Toast.LENGTH_LONG).show();
                }
                return;
        }

        intent.putExtra("url", url);
        startActivity(intent);
    }

    /**
     * 判断SD卡是否可用
     *
     * @return true : 可用<br>false : 不可用
     */
    public static boolean isSDCardEnable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }
}
